require("babel-polyfill");
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var MongoDB = require("./db.js");
var _ = require("lodash");
var crypto = require("crypto");

var JSONParser = bodyParser.json();

function getRandomSalt() {
    return Math.random().toString().slice(2, 12);
}

function cryptPwd(password, salt) {
    var saltPassword = password + "+1PazWlw==" + salt;
    var md5 = crypto.createHash("md5");
    var result = md5.update(saltPassword).digest("base64");
    return result;
}

app.use(express.static(path.resolve("../dist")));
app.use(cookieParser());

app.get("/", function (req, res) {
    res.sendFile(path.resolve("../dist/index.html"));
});

app.post("/confirm", JSONParser, function (req, res) {
    var response = {
        "username": req.body["usr"],
        "password": req.body["pass"],
        "recaptcha": req.body["g-recaptcha-response"]
    };
    MongoDB.dbQuery({
        "username": req.body["usr"]
    }, function (queryedRes) {
        if (_.isEmpty(queryedRes)) {
            response["success"] = false;
            response["usernamePass"] = false;
            response["passwordPass"] = false;
            return;
        }
        response["usernamePass"] = true;
        if (queryedRes[0]["password"] == cryptPwd(req.body["pass"], queryedRes[0]["salt"])) {
            response["success"] = true;
            response["passwordPass"] = true;
        } else {
            response["success"] = false;
            response["passwordPass"] = false;
        }
    });
    MongoDB.dbState.on("dbQueryOk", function () {
        console.log(req.body);
        res.end(JSON.stringify(response));
    });
});

app.post("/confirm1", JSONParser, function (req, res) {
    var response = {
        "username": req.body["usr"],
        "password": req.body["pass"],
        "recaptcha": req.body["g-recaptcha-response"]
    };
    var userData = new MongoDB.dbUser({
        username: req.body["usr"],
        salt: getRandomSalt()
    });
    userData.password = cryptPwd(req.body["pass"], userData.salt);
    MongoDB.dbQuery({
        "username": req.body["usr"]
    }, function (queryedRes) {
        response["success"] = false;
        if (_.isEmpty(queryedRes)) {
            response["success"] = true;
            MongoDB.dbInsert(userData);
        }
    });
    MongoDB.dbState.on("dbQueryOk", function () {
        console.log(response);
        res.end(JSON.stringify(response));
    });
});

var server = app.listen(80, function () {

    var host = server.address().address;
    var port = server.address().port;

    console.log(`Server running on ${host}:${port}`);

});
